//
// Created by 11510 on 2024/6/9.
//

#include "Stack.h"
#include <string.h>
#include <iostream>
using std::cout;
using std::endl;
/**
 * 无参构造
 */
Stack::Stack():
_elements(new int[10]()), _size(0), _capacity(10), _top(-1){

}

/**
 * 有参构造
 * @param capacity
 */
Stack::Stack(int capacity):
_elements(new int[capacity]()), _size(0), _capacity(capacity), _top(-1){
}
/**
 * 是否为空
 * @return
 */
bool Stack::empty(){
    return _top == -1;
}

/**
 * 是否栈满
 * @return
 */
bool Stack::full(){
    return _size == _capacity;
}

/**
 * get the top of stack
 * @return
 */
int Stack::top() {
    if(empty()){
        cout << "stack is empty!" << endl;
        return 0x7fffffff;
    }
    return _elements[_top];
}

/**
 * 入栈
 * @param elem
 */
void Stack::push(int elem) {
    if(full()){
//        TODO resize
        cout << "stack over flow" << endl;
        return;
    }

    _elements[++_top] = elem;
    _size++;
}

/**
 * 出栈
 */
void Stack::pop() {
    if(empty()){
        cout << "stack is empty" << endl;
        return;
    }

    _top--;
    _size--;
}

/**
 * 析构函数
 */
Stack::~Stack(){
    delete[] _elements;
    cout << "~ stack" << endl;
}

/**
 * 极易错，拷贝构造
 * @param rhs
 */
Stack::Stack(const Stack &rhs) {
    _elements = new int[rhs._capacity]();
    memcpy(_elements, rhs._elements, sizeof(int) * rhs._size);

    _size = rhs._size;
    _capacity = rhs._capacity;
    _top = rhs._top;
}

/**
 * 重载赋值运算符
 * @param rhs
 * @return
 */
Stack& Stack::operator=(const Stack &rhs){
    if(&rhs != this){
        delete [] _elements;
        _elements = new int[rhs._capacity]();
        memcpy(_elements, rhs._elements, sizeof(int) * rhs._size);

        _size = rhs._size;
        _capacity = rhs._capacity;
        _top = rhs._top;
    }
    return *this;
}

